package org.zuma.gradle.springboot.spec;

import lombok.Data;
import lombok.experimental.Accessors;
import org.gradle.api.Action;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.MapProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Nested;
import org.gradle.api.tasks.Optional;

import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;

public abstract class DockerSpec {


    final DockerRegistryConfigSpec publishRegistry;

    @Inject
    public DockerSpec(ObjectFactory objects) {
        this.publishRegistry = objects.newInstance(DockerRegistryConfigSpec.class);
    }

    DockerSpec(DockerRegistryConfigSpec publishRegistry) {
        this.publishRegistry = publishRegistry;
    }

    @Input
    @Optional
    public abstract MapProperty<String, Map<String, String>> getBuilderRegistry();

    public Map<String, BuildDockerRegistry> parseBuilderRegistry() {
        Map<String, BuildDockerRegistry> map = new HashMap<>();
        if (this.getBuilderRegistry() != null) {
            for (Map.Entry<String, Map<String, String>> entry : this.getBuilderRegistry().get().entrySet()) {
                var buildDockerRegistry = new BuildDockerRegistry();
                buildDockerRegistry.setUsername(entry.getValue().get("username"));
                buildDockerRegistry.setPassword(entry.getValue().get("password"));
                map.put(entry.getKey(), buildDockerRegistry);
            }
        }
        return map;
    }

    /*@Nested
    public Map<String, DockerRegistryConfigSpec> getBuilderRegistry() {
        return this.builderRegistry;
    }

    public void builderRegistry(Action<Map<String, DockerRegistryConfigSpec>> action) {
        action.execute(this.builderRegistry);
    }*/


    @Nested
    public DockerRegistryConfigSpec getPublishRegistry() {
        return this.publishRegistry;
    }


    public void publishRegistry(Action<DockerRegistryConfigSpec> action) {
        action.execute(this.publishRegistry);
    }




    public static abstract class DockerRegistryConfigSpec {

        @Input
        @Optional
        public abstract Property<String> getUsername();

        @Input
        @Optional
        public abstract Property<String> getPassword();

        @Input
        @Optional
        public abstract Property<String> getUrl();

        @Input
        @Optional
        public abstract Property<String> getEmail();
    }

    @Accessors(chain = true)
    @Data
    public static class BuildDockerRegistry {
        private String username;
        private String password;
    }
}
